package com.xw.echo.core.serializer;
import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class HessianSerializar implements Serializar {
  @Override
    public byte[] serializar(Object obj) throws Exception {
        if (obj == null) {
            return null; // 处理 null 对象的情况
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Hessian2Output out = new Hessian2Output(bos);
        out.writeObject(obj);
        out.flush(); // 确保所有数据都写入到底层流
        out.close(); // 关闭输出流
        return bos.toByteArray();
    }

    @Override
    public Object deserializar(byte[] bytes) throws Exception {
        if (bytes == null || bytes.length == 0) {
            return null; // 处理 null 或空字节数组的情况
        }
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Hessian2Input in = new Hessian2Input(bis);
        Object obj = in.readObject();
        in.close(); // 关闭输入流
        return obj;
    }
}
